const ErrorCode = require('../utils/ErrorCode')
const ResultVo = require('../utils/ResultVo')
const Exception = require('../exception/Exception')
const sendMail = require('../utils/SendEmail')
const { getValue, setValue } = require('../utils/Redis')
const UserService = require('../service/UserService')
const bcrypt = require('bcryptjs')
const { random, genToken } = require('../utils/util')

class UserController {

  async signup(req, res, next) {
    const { email, code, password } = req.body
    const value = await getValue(email).catch(err => next(new Exception(-1, err, { code: '验证码错误' })))
    if (value !== code.toUpperCase()) return next(new Exception(10003, ErrorCode[10003], { code: '验证码错误' }))
    const salt = bcrypt.genSaltSync(10)
    const _password = bcrypt.hashSync(password, salt)
    const name = random(8)
    const result = await UserService.create({ email, password: _password, name: `juejin用户${name}` }).catch(err => next(err))
    console.log(result)
    res.json(ResultVo.successNull())
  }

  async getCode(req, res, next) {
    const { email } = req.body
    const code = Math.random().toString(36).substr(-4, 4).toUpperCase()
    setValue(email, code, 3600)
    const result = await sendMail({ email, code }).catch(err => next(err))
    res.json(ResultVo.success(result))
  }

  async signin(req, res, next) {
    const { email, password } = req.body
    const user = await UserService.findByEmail(email).catch(err => next(new Exception(-1, err)))
    console.log(user)
    if (!bcrypt.compareSync(password, user.password)) return next(new Exception(10004, ErrorCode[10004], { password: '密码错误' }))
    const token = genToken({ id: user._id, name: user.name })
    res.json(ResultVo.success({ token }))
  }

  async searchUser(req, res, next) {
    const { name } = req.body
    const result = await UserService.findByName(name).catch(err => next(new Exception(-1, err)))
    res.json(ResultVo.success(result))
  }

  async editUser(req, res, next) {
    const data = req.body
    for(let i of data) {
      if (data[i] == '' || data[i] == null) {
        delete data[i]
      }
    }

    const result = await UserService.updateUser(data).catch(err => next(err))
    res.json(ResultVo.success(result))
  }
}

module.exports = new UserController();